/**
 * 计划管理 - 发运计划
 * @author xiaoxujs
 */
import {
    useNavigate
} from 'react-router-dom'
import { ShippingPlanBox } from "./style";
import SearchModule from './components/SearchModule'
import { Button, ConfigProvider, Dropdown, MenuProps, message, Popconfirm, Space, Table, TableProps, Tabs, TabsProps, Tooltip } from "antd";
import { useWindowFontSize } from "../../../assets/fun/Antd/configprovider";
import { IPlanPlanPage, IPlanPlanPageParams, IPlanPlanPageSearchForm } from "../../../type/planManagement";
import { useCallback, useEffect, useState } from "react";
import { getPlanDelete, getPlanGoodsNames, getPlanTransportNames, postPlanPlanPage } from "../api";
import { IFenye, INoFenye } from "../../../type/commit";
import { handleGetDictionaryItemData } from "../../../assets/fun/DictionaryItem";
import { dictionaryStyle } from "../../../assets/style/DictionaryItem";
import { ISelectList, TablePaginationPosition } from "../../../type/antd";
import AddPlanModule from "./components/AddPlanModule";
import dayjs from "dayjs";
import SupplementPlanModule from './components/SupplementPlanModule';
import ToVoidModule from "./components/ToVoidModule"; // 作废计划
import { DownOutlined } from '@ant-design/icons';

const ShippingPlan = () => {

    const contentValue: TablePaginationPosition = "bottomCenter"; //位置

    const navigate = useNavigate();

    const [listData, setListData] = useState<IPlanPlanPage[]>([]);
    const [paging, setPaging] = useState({
        currentPage: 1,
        pageSize: 3,
    });
    const [total, setTotal] = useState(0);
    const [tableLoading, setTableLoading] = useState(false); //tableLoading
    const [planStateValue, setPlanStateValue] = useState('0'); // 选中tabs
    const [goodsList, setGoodsList] = useState<ISelectList[]>([]); //  货品下拉数据
    const [transportNameList, setTransportNameList] = useState<ISelectList[]>([]); //物流单位数据
    const [addPlanShow, setAddPlanShow] = useState(false); //  增加计划
    const [searchValue, setSearchValue] = useState<IPlanPlanPageSearchForm>(); //设置
    const [supplementPlanShow, setSupplementPlanShow] = useState(false); // 补充计划弹窗
    const [clickData, setClickData] = useState<IPlanPlanPage>(); // 点击数据
    const [toVoidShow, setToVoidShow] = useState(false); //作废原因
    const [clickId, setClickId] = useState<string>(); // 点击ID



    const zhidianFun = useCallback(async () => {
        const goodsValue = await getPlanGoodsNames() as INoFenye<string>;
        if (goodsValue.code === 20000) {
            let arrGoods: ISelectList[] = []
            goodsValue.data.forEach(element => {
                arrGoods.push({
                    value: element,
                    label: element
                })
            });
            setGoodsList([...arrGoods]);
        } else {
            message.error(goodsValue.msg);
        }
        const { code, msg, data } = await getPlanTransportNames() as INoFenye<string>;
        if (code === 20000) {
            let arr: ISelectList[] = []
            data.forEach(element => {
                arr.push({
                    value: element,
                    label: element
                })
            });
            setTransportNameList([...arr]);
        } else {
            message.error(msg);
        }
    }, []);

    useEffect(() => {
        zhidianFun();
    }, [zhidianFun])

    const listFun = useCallback(async (params: IPlanPlanPageParams) => {
        setTableLoading(true);
        const { code, msg, data } = (await postPlanPlanPage(
            params
        )) as IFenye<IPlanPlanPage>;
        if (code === 20000) {
            setListData(data.records);
            setPaging({
                currentPage: params.currentPage,
                pageSize: params.pageSize,
            })
            setTotal(data.total);
            setTableLoading(false);
            setPlanStateValue(params.planState);
        } else {
            message.error(msg);
        }
    }, []);
    useEffect(() => {
        const params = {
            planState: '0',
            currentPage: 1,
            pageSize: 10
        }
        listFun(params);
    }, [listFun])

    // 表单切换
    const handleTabsChange = (key: string) => {
        const params = {
            planState: key,
            currentPage: 1,
            pageSize: 10,
            goodsName: searchValue && searchValue.goodsName,
            transportName: searchValue && searchValue.transportName,
            startDate: searchValue && searchValue.date ? dayjs(searchValue.date[0]).format('YYYY-MM-DD') : undefined,
            stopDate: searchValue && searchValue.date ? dayjs(searchValue.date[1]).format('YYYY-MM-DD') : undefined,

        }
        listFun(params);

    };
    // 添加
    const handleAddPlanCallback = () => {
        setAddPlanShow(false);

        const params = {
            planState: '0',
            currentPage: 1,
            pageSize: 10
        }
        listFun(params);
    }
    // 检索
    const handleSearchCallback = (value?: IPlanPlanPageSearchForm) => {
        if (value) {
            const params: IPlanPlanPageParams = {
                planState: planStateValue,
                currentPage: 1,
                pageSize: 10,
                goodsName: value.goodsName,
                transportName: value.transportName,
                startDate: value.date ? dayjs(value.date[0]).format('YYYY-MM-DD') : undefined,
                stopDate: value.date ? dayjs(value.date[1]).format('YYYY-MM-DD') : undefined,
            }
            listFun(params);

        } else {
            const params = {
                planState: planStateValue,
                currentPage: 1,
                pageSize: 10
            }
            listFun(params);
        }
        setSearchValue(value);
    }
    // 补量回调
    const handleSupplementPlanCallback = () => {
        setClickData(undefined);
        setSupplementPlanShow(false);
        const params = {
            planState: planStateValue,
            currentPage: paging.currentPage,
            pageSize: paging.pageSize,
            goodsName: searchValue && searchValue.goodsName,
            transportName: searchValue && searchValue.transportName,
            startDate: searchValue && searchValue.date ? dayjs(searchValue.date[0]).format('YYYY-MM-DD') : undefined,
            stopDate: searchValue && searchValue.date ? dayjs(searchValue.date[1]).format('YYYY-MM-DD') : undefined,
        }
        listFun(params)
    }
    //  作废
    const handleToVoidCallback = () => {
        setToVoidShow(false);
        setClickId(undefined);
        const params = {
            planState: planStateValue,
            currentPage: paging.currentPage,
            pageSize: paging.pageSize,
            goodsName: searchValue && searchValue.goodsName,
            transportName: searchValue && searchValue.transportName,
            startDate: searchValue && searchValue.date ? dayjs(searchValue.date[0]).format('YYYY-MM-DD') : undefined,
            stopDate: searchValue && searchValue.date ? dayjs(searchValue.date[1]).format('YYYY-MM-DD') : undefined,
        }
        listFun(params)
    }
    const confirm = async (id: string) => {
        const { code, msg } = await getPlanDelete({ id }) as { code: number; msg: string };
        if (code === 20000) {
            message.success('删除成功');
            const params = {
                planState: planStateValue,
                currentPage: paging.currentPage,
                pageSize: paging.pageSize,
                goodsName: searchValue && searchValue.goodsName,
                transportName: searchValue && searchValue.transportName,
                startDate: searchValue && searchValue.date ? dayjs(searchValue.date[0]).format('YYYY-MM-DD') : undefined,
                stopDate: searchValue && searchValue.date ? dayjs(searchValue.date[1]).format('YYYY-MM-DD') : undefined,
            }
            listFun(params)
        } else {
            message.error(msg);
        }
    };

    const itemsButton: (record: IPlanPlanPage) => MenuProps['items'] = (record) => [
        {
            key: '1',
            label: <Button type="link" onClick={() => {
                setSupplementPlanShow(true);
                setClickData(record)
            }}>补充计划量</Button>,
        },
        {
            key: '2',
            label: <Button type="link" onClick={() => {
                setToVoidShow(true);
                setClickId(record.id)
            }}>作废</Button>,
        },
    ]

    const pagination = {
        //分页
        position: [contentValue],
        //是否可以改变pagesize//
        showSizeChanger: true,
        //是否可以快速跳转到某页
        showQuickJumper: true,
        //展示一共有多少条数据//
        showTotal: () => `共${total}条`,
        //每页条数
        pageSize: paging.pageSize,
        //当前页数
        current: paging.currentPage,
        //数据总数
        total: total,
        //页码改变的回调，参数是改变后的页码及每页条数
        onChange: (current: number, pageSize: number) => {
            const params = {
                planState: planStateValue,
                currentPage: current,
                pageSize: pageSize,
                goodsName: searchValue && searchValue.goodsName,
                transportName: searchValue && searchValue.transportName,
                startDate: searchValue && searchValue.date ? dayjs(searchValue.date[0]).format('YYYY-MM-DD') : undefined,
                stopDate: searchValue && searchValue.date ? dayjs(searchValue.date[1]).format('YYYY-MM-DD') : undefined,
            }
            listFun(params)
        },
    };
    const columns: TableProps<IPlanPlanPage>['columns'] = [
        {
            title: '序号',
            align: 'center',
            render: (_, record, index) => (
                <span>{(paging.currentPage - 1) * paging.pageSize + index + 1}</span>
            ),
        },
        {
            title: '计划编号',
            dataIndex: 'planNo',
            align: 'center',
        },
        {
            title: '计划状态',
            dataIndex: 'planState',
            align: 'center',
            render: (text, record) => {
                const obj = handleGetDictionaryItemData('JHZT', text);
                if (obj === '无') {
                    return <span>--</span>
                } else {
                    return <Tooltip title={record.cancelReason}>
                        <div style={dictionaryStyle[obj.listClass]}>
                            {obj.cssClass ? <span className='iconfont' style={{ marginRight: '0.5rem' }} dangerouslySetInnerHTML={{ __html: obj.cssClass }}></span> : null}
                            {obj.label}
                        </div>
                    </Tooltip>
                }

            }
        },
        {
            title: '计划日期',
            align: 'center',
            render: (_, record) => <span>{record.startDate}~{record.stopDate}</span>
        },
        {
            title: '货品',
            dataIndex: 'goodsName',
            align: 'center',
        },
        {
            title: '物流单位',
            dataIndex: 'transportName',
            align: 'center',
        },
        {
            title: '计划量(吨)',
            dataIndex: 'planQuantity',
            align: 'center',
        },
        {
            title: '剩余量(吨)',
            dataIndex: 'remainingQuantity',
            align: 'center',
        },
        {
            title: '审核状态',
            dataIndex: 'approvalState',
            align: 'center',
            render: text => {
                const obj = handleGetDictionaryItemData('SHZT', text);
                if (obj === '无') {
                    return <span>--</span>
                } else {
                    return <div style={dictionaryStyle[obj.listClass]}>
                        {obj.cssClass ? <span className='iconfont' style={{ marginRight: '0.5rem' }} dangerouslySetInnerHTML={{ __html: obj.cssClass }}></span> : null}
                        {obj.label}
                    </div>
                }

            }
        },
        {
            title: '审核结果',
            dataIndex: 'approvalResult',
            align: 'center',
            render: (text, record) => {
                const obj = handleGetDictionaryItemData('SHJG', text);
                if (obj === '无') {
                    return <span>--</span>
                } else {
                    return <Tooltip title={record.approvalReason}>
                        <div style={dictionaryStyle[obj.listClass]}>
                            {obj.cssClass ? <span className='iconfont' style={{ marginRight: '0.5rem' }} dangerouslySetInnerHTML={{ __html: obj.cssClass }}></span> : null}
                            {obj.label}
                        </div>
                    </Tooltip>
                }

            }
        },
        {
            title: ' 操作',
            align: "center",
            render: (_, record) => planStateValue === '0' ? <>
                <Button type="link" onClick={() => navigate('/home/planManagement/shippingPlan/shippingReport', {
                    state: {
                        data: record
                    }
                })}>发运报表</Button>
                <Button type="link" onClick={() => navigate('/home/planManagement/shippingPlan/vehicleManagement', {
                    state: {
                        planNo: record.planNo,
                        data: record
                    }
                })}>导入车辆</Button>
                <Dropdown menu={{ items: itemsButton(record) }}>
                    <Button type="link">
                        <Space>
                            更多
                            <DownOutlined />
                        </Space>
                    </Button>

                    {/* </a> */}
                </Dropdown>


            </> : <Popconfirm
                title="确定要删除当前数据吗"
                onConfirm={() => confirm(record.id)}
                // onCancel={cancel}
                okText="删除"
                cancelText="取消"
            >
                <Button type="link">删除</Button>
            </Popconfirm>
        },
    ];

    // 表格
    const JihuaTable = () => {
        return <ConfigProvider theme={{
            components: {
                Table: {
                    headerColor: '#8B9BAC',
                    cellFontSize: useWindowFontSize(14),
                    cellPaddingBlock: 7
                }
            }
        }}>
            <Table<IPlanPlanPage>
                pagination={pagination}
                rowKey='id'
                columns={columns}
                dataSource={listData}
                loading={tableLoading}
            />
        </ConfigProvider>
    }
    const items: TabsProps['items'] = [
        {
            key: '0',
            label: '正常计划',
            children: JihuaTable(),
        },
        {
            key: '1',
            label: '作废计划',
            children: JihuaTable(),
        }
    ];
    //  tabs 标签右边操作模块
    const operations = <Button type='primary' icon={<span className="iconfont">&#xe620;</span>} onClick={() => setAddPlanShow(true)}>增加计划</Button>
    return <ShippingPlanBox>
        <div className="title">
            发运计划
        </div>
        <SearchModule goodsList={goodsList} transportNameList={transportNameList} handleCallback={handleSearchCallback} />
        <Tabs activeKey={planStateValue} tabBarExtraContent={operations} items={items} onChange={handleTabsChange} />
        {/* 添加计划 */}
        <AddPlanModule open={addPlanShow} handleCallback={handleAddPlanCallback} goodsList={goodsList} transportNameList={transportNameList} />
        {/* 补充计划量 */}
        <SupplementPlanModule open={supplementPlanShow} clickData={clickData} handleCallback={handleSupplementPlanCallback} />
        {/* 作废计划 */}
        <ToVoidModule open={toVoidShow} handleCallback={handleToVoidCallback} clickId={clickId} />
    </ShippingPlanBox>
}

export default ShippingPlan;